package pemks;

import jakarta.servlet.DispatcherType;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import pemks.filter.AuthFilter;
import pemks.servlet.FileServlet;
import pemks.servlet.LocalServlet;
import pemks.servlet.UserServlet;

import java.io.InputStream;
import java.util.EnumSet;
import java.util.Properties;

/**
 * @description:  
 * @author kl
 * @date 2025/4/4 下午11:11
 * @version 1.0
 */
public class ServerStarter {
    private static final int DEFAULT_PORT = 8080;
    public static String DB_URL;
    public static String DB_USER;
    public static String DB_PASS;

    public static void main(String[] args) throws Exception {
        // 读取配置文件
        Properties prop = new Properties();
        try (InputStream input = ServerStarter.class.getResourceAsStream("/application.properties")) {
            prop.load(input);
        }

        int port = Integer.parseInt(prop.getProperty("server.port", String.valueOf(DEFAULT_PORT)));
        DB_URL= prop.getProperty("db.url");
        DB_USER = prop.getProperty("db.user");
        DB_PASS = prop.getProperty("db.password");

        // 创建嵌入式服务器
        Server server = new Server(port);

        // 配置Servlet上下文
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        // 注册过滤器
        context.addFilter(AuthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

        // 注册Servlet
        context.addServlet(LocalServlet.class,"/local/*");
        context.addServlet(UserServlet.class, "/smartgrid/*");
        context.addServlet(FileServlet.class, "/file/*");

        server.setHandler(context);
        server.start();
        System.out.println("Server started on port: " + port);
        server.join();
    }
}
